namespace WP7Contrib.View.Controls.Extensions
{
    using System;
    using System.Linq;

    using Microsoft.Phone.Shell;

    public static class ApplicationBarExtensions
    {
        public static ApplicationBarIconButton FindButton(this IApplicationBar applicationBar, string text)
        {
            return applicationBar.FindButton(text, false);
        }

        public static ApplicationBarIconButton FindButton(
            this IApplicationBar applicationBar, string text, bool throwIfNotFound)
        {
            if (applicationBar == null)
            {
                throw new ArgumentNullException("applicationBar");
            }

            ApplicationBarIconButton button =
                applicationBar.Buttons.Cast<object>().Select(o => o as ApplicationBarIconButton).FirstOrDefault(
                    item => item != null && item.Text == text);

            if (throwIfNotFound && button == null)
            {
                throw new IndexOutOfRangeException(string.Format("Unable to find Button: {0}", text));
            }

            return button;
        }

        public static ApplicationBarMenuItem FindMenuItem(this IApplicationBar applicationBar, string text)
        {
            return applicationBar.FindMenuItem(text, false);
        }

        public static ApplicationBarMenuItem FindMenuItem(
            this IApplicationBar applicationBar, string text, bool throwIfNotFound)
        {
            if (applicationBar == null)
            {
                throw new ArgumentNullException("applicationBar");
            }

            ApplicationBarMenuItem menuItem =
                applicationBar.MenuItems.Cast<object>().Select(o => o as ApplicationBarMenuItem).FirstOrDefault(
                    item => item != null && item.Text == text);

            if (throwIfNotFound && menuItem == null)
            {
                throw new IndexOutOfRangeException(string.Format("Unable to find MenuItem: {0}", text));
            }

            return menuItem;
        }
    }
}